package com.example.sherlockzhong.plush_v2.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by SherlockZhong on 9/11/14.
 */
public class DateTimeUtil {

    public static String getCurrentTime(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }

    public static String getScoolYearStart() {
//        try {
//            JSONTokener jsonTokener = new JSONTokener(NetworkUtils.httpGet("http://plush.scauhci.org/api/v1/index.php/ZF/getStartDate"));
//            JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
//            return jsonObject.get("start_date").toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return "2014-09-15";
    }

    public static long getWeekNumberOfSchoolYear() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(getScoolYearStart()));
            long startTime = cal.getTimeInMillis();
            cal.setTime(new Date());
            long currentTime = cal.getTimeInMillis();
            return ((currentTime - startTime) / (1000 * 3600 * 24) / 7) + 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int getWeekdayIndex() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            return 6;
        } else {
            return cal.get(Calendar.DAY_OF_WEEK) - 2;
        }
    }

    public static long getDayGap(String day1, String day2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(day1));
            long dayOne = cal.getTimeInMillis();
            cal.setTime(sdf.parse(day2));
            long dayTwo = cal.getTimeInMillis();
            return Math.abs(dayOne - dayTwo) / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long getTimeGap(String time1, String time2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse("2000-01-01 " + time1 + ":00"));
            long timeOne = cal.getTimeInMillis();
            cal.setTime(sdf.parse("2000-01-01 " + time2 + ":00"));
            long timeTwo = cal.getTimeInMillis();
            return Math.abs(timeOne - timeTwo) / (1000 * 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getClassStartTime(String classOrder) {
        HashMap<String, String> classesTime = new HashMap<String, String>();
        classesTime.put("1,2节", "08:00");
        classesTime.put("3,4节", "10:05");
        classesTime.put("5,6节", "12:25");
        classesTime.put("7,8节", "14:30");
        classesTime.put("9,10节", "16:35");
        classesTime.put("11,12节", "19:30");
        classesTime.put("11,12,13节", "19:30");
        classesTime.put("99,100节", getCurrentTime("HH:mm"));
        return classesTime.get(classOrder).toString();
    }

    public static HashMap decodeClassTime(String classTime, int weekdayIndex, int classIndex) {
        HashMap<String, String> result = new HashMap<String, String>();

//        String[] weekdays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
//        String[] classes = {"1,2节", "3,4节", "5,6节", "7,8节", "9,10节", "11,12节", "11,12,13节"};
        String[] weekdays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

        ArrayList classes = new ArrayList();
        classes.add("1,2节");
        classes.add("3,4节");
        classes.add("5,6节");
        classes.add("7,8节");
        classes.add("9,10节");
        classes.add("11,12节");
        classes.add("11,12,13节");

        String[] classTimeParts = classTime.split(" ");
        String classTimeMain = classTimeParts[0];

        result.put("weekday", weekdays[weekdayIndex]);
        result.put("weekdayIndex", "" + weekdayIndex);

        if (classTimeMain.indexOf("3节/周") >= 0) {
            result.put("classOrder", classes.get(6).toString());
        } else {
            result.put("classOrder", classes.get(classIndex).toString());
        }

        String weeksString = "";
        if (classTimeParts.length > 1) {
            for (int i = 0; i < classTimeParts.length; i++) {
                weeksString += getWeeksOfClassTime(classTimeParts[i]);
            }
        } else {
            weeksString += getWeeksOfClassTime(classTimeMain);
        }
        result.put("weeks", weeksString.substring(0, weeksString.length() - 1));
        result.put("weeksSumary", getWeeksSumary(classTime));

        return result;
    }

    public static String getWeeksOfClassTime(String classTime) {
        String result = "";

        int bracketStart = classTime.indexOf("{") + 2;
        int bracketEnd = classTime.indexOf("}") - 1;
        String weekRange = classTime.substring(bracketStart, bracketEnd);
        if (weekRange.indexOf("单") >= 0 || weekRange.indexOf("双") >= 0) {
            String tmpRange = weekRange.substring(0, weekRange.length() - 3);
            String string = tmpRange.split("-")[0];
            int startWeek = Integer.parseInt(string);
            string = tmpRange.split("-")[1];
            int endWeek = Integer.parseInt(string);
            for (int j = startWeek; j <= endWeek; j += 2) {
                if (j < 10) {
                    result += "0";
                }
                result += j + ",";
            }
        } else {
            if (weekRange.indexOf("节/") >= 0) {
                int weeksEnd = weekRange.indexOf("周");
                weekRange = weekRange.substring(0, weeksEnd);
            }
            int startWeek = Integer.parseInt(weekRange.split("-")[0]);
            int endWeek = Integer.parseInt(weekRange.split("-")[1]);
            for (int j = startWeek; j <= endWeek; j++) {
                if (j < 10) {
                    result += "0";
                }
                result += j + ",";
            }
        }
        return result;
    }

    public static String getWeeksSumary(String classTime) {
        String result = "";
        String[] classTimeParts = classTime.split(" ");
        for (int i = 0; i < classTimeParts.length; i++) {
            result += decodeWeeksSumary(classTimeParts[i]);
        }
        return result.substring(0, result.length() - 1);
    }

    public static String decodeWeeksSumary(String time) {
        String result = "";
        int weekStart = time.indexOf("{第") + 2;
        int weekEnd;
        if (time.contains("节/周}")) {
            weekEnd = time.indexOf("周|");
        } else {
            weekEnd = time.indexOf("周}");
        }
        result = time.substring(weekStart, weekEnd) + "周 ";
        return result;
    }

    public static HashMap decodeExamTime(String time) {
        HashMap<String, String> result = new HashMap<String, String>();

        if (time.contains("第")) {
            // 获取考试年月日
            String rawDate = time.split(" ")[0];
            int dateStart = rawDate.indexOf("(") + 1;
            int dateEnd = rawDate.length() - 1;
            String date = rawDate.substring(dateStart, dateEnd);
            String[] dateParts = date.split("-");
            result.put("year", dateParts[0]);
            result.put("month", dateParts[1]);
            result.put("day", dateParts[2]);

            // 获取考试开始和结束时间
            String times = time.split(" ")[1];
            String[] timesParts = times.split("-");
            result.put("start_time", timesParts[0]);
            result.put("end_time", timesParts[1]);
        } else {
            // 获取考试年月日
            int yearPos = time.indexOf("年");
            int monthPos = time.indexOf("月");
            int dayPos = time.indexOf("日");
            result.put("year", time.substring(0, yearPos));
            result.put("month", time.substring(yearPos + 1, monthPos));
            result.put("day", time.substring(monthPos + 1, dayPos));

            // 获取考试开始和结束时间
            int timesStart = time.indexOf("(") + 1;
            int timesEnd = time.indexOf(")");
            String times = time.substring(timesStart, timesEnd);
            String[] timesParts = times.split("-");
            result.put("start_time", timesParts[0]);
            result.put("end_time", timesParts[1]);
        }

        return result;
    }

    public static boolean timeIsPast (String time) {
        Pattern timePatern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}");
        Matcher timeMatcher = timePatern.matcher(time);
        if (!timeMatcher.matches()) {
            return false;
        }

        String currentDateTime = getCurrentTime("yyyy-MM-dd HH:mm");
        String currentDate = currentDateTime.split(" ")[0];
        String currentTime = currentDateTime.split(" ")[1];
        String[] currentDateParts = currentDate.split("-");
        String[] currentTimeParts = currentTime.split(":");
        int currentYear = Integer.parseInt(currentDateParts[0]);
        int currentMonth = Integer.parseInt(currentDateParts[1]);
        int currentDay = Integer.parseInt(currentDateParts[2]);
        int currentHour = Integer.parseInt(currentTimeParts[0]);
        int currentMinute = Integer.parseInt(currentTimeParts[1]);

        String targetDate = time.split(" ")[0];
        String targetTime = time.split(" ")[1];
        String[] targetDateParts = targetDate.split("-");
        String[] targetTimeParts = targetTime.split(":");
        int targetYear = Integer.parseInt(targetDateParts[0]);
        int targetMonth = Integer.parseInt(targetDateParts[1]);
        int targetDay = Integer.parseInt(targetDateParts[2]);
        int targetHour = Integer.parseInt(targetTimeParts[0]);
        int targetMinute = Integer.parseInt(targetTimeParts[1]);

        return targetYear < currentYear ||
               (targetYear == currentYear && targetMonth < currentMonth) ||
               (targetYear == currentYear && targetMonth == currentMonth && targetDay < currentDay) ||
               (targetYear == currentYear && targetMonth == currentMonth && targetDay == currentDay && targetHour < currentHour) ||
               (targetYear == currentYear && targetMonth == currentMonth && targetDay == currentDay && targetHour == currentHour && targetMinute < currentMinute);
    }

}
